<?PHP

namespace SDF\Core;
use \SDF\Core\Config;

/**
 * 路由
 * @package SDF\Core
 */
class Route
{
    /**
     * @throws \Exception
     */
    public static function route_start() {
        $parse_info = self::parseUrl();
        $GLOBALS['PARSE_INFO'] = $parse_info;

        if(!defined('__ROOT__')){
            define('__ROOT__','/');
        }
        if(!defined('__CONTROLLER__')){
            define('__CONTROLLER__',__ROOT__.$parse_info['control']);//__CONTROLLER__（__或者__URL__ 兼容考虑）： 前控制器的URL地址（不含域名）
        }
        if(!defined('__URL__')){
            define('__URL__',__CONTROLLER__);
        }
        if(!defined('__ACTION__')){//__ACTION__：当前操作的URL地址 （不含域名）
            define('__ACTION__',__CONTROLLER__.'/'.$parse_info['action']);
        }
        $ControllersClassName = Config::get('ctrl_path', 'Controllers') . '\\' . $parse_info['control'];//控制器名字
        if (!\class_exists($ControllersClassName)) {
            throw new \Exception("no class {$ControllersClassName}",404);
        }
        $ControllersClassObj = new $ControllersClassName();
        if (method_exists($ControllersClassObj, '_remap')) {
            $ControllersClassObj->_remap($parse_info['action'], $parse_info['aPathInfo']);
        } else {
            if (!method_exists($ControllersClassObj, $parse_info['action'])) {
                throw new \Exception('找不到方法：' . $parse_info['control'] . '->' . $parse_info['action'] . '()',404);
            }
            call_user_func_array(array(&$ControllersClassObj, $parse_info['action']), $parse_info['aPathInfo']);
        }
    }
    public static function parseUrl(){
        $data['control'] = Config::get('default_control', 'index');//默认控制器
        $data['action'] = Config::get('default_action', 'index');//默认方法
        $data['aPathInfo'] =array();
        /*if (empty($_SERVER['HTTP_HOST'])) {//cli模式运行
            $argv = $_SERVER['argv'];
            array_shift($argv);
            if(is_array($argv) and count($argv)>0){
                $data['control'] = array_shift($argv);
            }
            if(is_array($argv) and count($argv)>0){
                $data['action'] = array_shift($argv);
            }
            if(is_array($argv) and count($argv)>0){
                $data['aPathInfo'] = $argv;
            }
            return $data;
        }*/

        if(isset($_GET['s'])){
            $arr = explode('.',$_GET['s']);
        }elseif(isset($_SERVER['PATH_INFO'])){
            $arr = explode('.',$_SERVER['PATH_INFO']);
        }else{
            return $data;
        }
        $aPathInfo = explode('/', trim($arr[0],'/'));
        unset($arr);
        $data['control'] = (empty($aPathInfo[0]) ? $data['control']: $aPathInfo[0]);
        array_shift($aPathInfo);
        $data['action'] = (isset($aPathInfo[0]) ? $aPathInfo[0] : $data['action']);
        array_shift($aPathInfo);
        $data['aPathInfo'] = $aPathInfo;
        return $data;
    }
}